﻿using System;
using System.Configuration;
using LaxCraft.Attributes;
using LaxCraft.Domain;
using LaxCraft.Helpers;

namespace LaxCraft.Controllers
{
	using System.Web.Mvc;
    using System.Linq;
	using LaxCraft.Repositories;

	public class PostController : Controller
	{
		private readonly IPostRepository blog;

        public PostController(IPostRepository blog)
		{
			this.blog = blog;
		}

        public ActionResult Index()
        {
            ViewBag.Posts = blog.GetPosts().OrderByDescending(p => p.CreatedOn);
            ViewBag.Admin = LaxCraftSession.CurrentUser.IsAdministrator;

            return View(ViewBag);

        }

        public ActionResult Create()
        {
            return View();
        }

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Create(Post post)
        {
            if (ModelState.IsValid)
            {

                var newPost = new Post { Body = post.Body, Tags = post.Tags, Title = post.Title, CreatedBy = post.CreatedBy, CreatedOn = DateTime.Now };
                blog.Save(newPost);

                return RedirectToAction("Index");
            }

            return View(post);
        }

        public ActionResult Edit(int id)
        {
            if (!LaxCraftSession.CurrentUser.IsAdministrator)
                return Details(id);

            Post post = blog.GetPosts().Where(p => p.Id == id).FirstOrDefault();
            return View(post);
        }

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Edit(Post updatedPost)
        {
            if (ModelState.IsValid)
            {
                var oldPost = blog.GetPosts().Where(p => p.Id == updatedPost.Id).FirstOrDefault();
                oldPost.Title = updatedPost.Title;
                oldPost.Body = updatedPost.Body;
                oldPost.CreatedBy = updatedPost.CreatedBy;
                oldPost.Tags = updatedPost.Tags;
                blog.Save(oldPost);
                return Index();
            }
            return View(updatedPost);
        }

        public ActionResult Details(int id)
        {
            ViewBag.Post = blog.GetPosts().Where(p => p.Id == id).FirstOrDefault();
            ViewBag.Admin = LaxCraftSession.CurrentUser.IsAdministrator;

            return View(ViewBag);
        }

        public ActionResult Delete(int id)
        {
            //ISession session = SQLiteUtil.SessionFactory.OpenSession();
            //Post post = session.Query<Post>().Single(p => p.Id == id);
            //if (null != post)
            //{
            //    using (var txn = session.BeginTransaction())
            //    {
            //        session.Delete(post);
            //        txn.Commit();
            //    }
            //}
            return RedirectToAction("Index");
        }

	}
}